/**
 * @description: 获取店铺账号信息 快手 （已废弃，windows系统下无法获取缓存信息）
 * @param {*} data
 * @param {*} hierarchy
 * @return {*}
 */
function getKSUserInfoFromLocal(data, hierarchy) {
  let userInfo = null;
  const { root, structure } = hierarchy;
  if (structure[root].length) {
    const CustomContainerKeys = structure[structure[root][0]];
    let arr = [];
    CustomContainerKeys.forEach((key) => {
      arr.push(...structure[key]);
    });
    arr.some((key) => {
      if (data[key] && data[key].fields && data[key].fields.shopFullName) {
        userInfo = data[key].fields;
        return true;
      } else {
        return false;
      }
    });
  }
  return userInfo;
}

/**
 * @description: 查看审核结果  抖店
 * @return {*}
 */
function checkAuditResultDD() {
  return new Promise((resolve, reject) => {
    try {
      ddGetReceiveInfoViewQuotaApplyInfo()
        .then((res) => {
          // ApplydeQuotaTimes  今日剩余提额次数
          // Status   1  无风险，可提额   2  解密额度已冻结，不可申请     4  请用完当日解密额度后再申请     6  您的提额申请正在审批中
          const { Status, ApplydeQuotaTimes } = res;
          userInfo.canApply = Status === 1 && Number(ApplydeQuotaTimes) > 0;

          ddApiGetQuota(userInfo.token)
              .then((res) => {
                const { used_quota, unused_quota } = res;
                userInfo.used_quota = used_quota;
                userInfo.unused_quota = unused_quota;
                $("#used_quota").text(used_quota);
                $("#unused_quota").text(unused_quota);
                // 调试
                if(userInfo.canApply){

                  ddApiGetQuotaApplyList(userInfo.token)
                  .then((re) => {
                    // 0 审核中 1 审核通过 2 审核不通过
                    if (pluginInfo.applicationNum === unused_quota) {
                      resolve(4);
                    } else if (re === 0) {
                      resolve(1);
                    } else if (re === 1) {
                      if (pluginInfo.applicationNum > unused_quota) {
                        resolve(3);
                      } else {
                        resolve(4);
                      }
                    } else if (re === 2) {
                      resolve(2);
                    } else {
                      resolve(5);
                    }
                  })
                  .catch((er) => {
                    reject(er);
                  });


                }else{
                  switch (Status) {
                    case 2:
                      resolve(5);
                      break;
                      case 4:
                        resolve(4);
                      break;
                      case 6:
                        resolve(1);
                      break;
                    default:
                      resolve(5);
                      break;
                  }
                }
                
              })
              .catch((err) => {
                reject(err);
              });
        })
        .catch((err) => {
          reject(err);
        });
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * @description: 查看审核结果  快手
 * @return {*}
 */
function checkAuditResultKS() {
  return new Promise((resolve, reject) => {
    ksApiGetQuota()
      .then(async (res) => {
        const {
          quota: { used_quota, unused_quota },
          canApply,
          applicationNum,
        } = res;
        userInfo.used_quota = used_quota;
        userInfo.unused_quota = unused_quota;
        pluginInfo.applicationNum = applicationNum;
        $("#used_quota").text(used_quota);
        $("#unused_quota").text(unused_quota);

        if (canApply && applicationNum > unused_quota + used_quota) {
          const status = await ksApiGetQuotaApplyList();
          switch (status) {
            case 3:
              resolve(3);
              break;
            default:
              resolve(4);
          }
        } else if (applicationNum === unused_quota + used_quota) {
          resolve(4);
        } else {
          resolve(5);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * @description: 申请提额  抖店
 * @return {*}
 */
function applyPromotionQuotaDD() {
  return new Promise((resolve, reject) => {
    const {
      applicationNum: apply_quota,
      desc: apply_description,
      reason,
      options,
    } = pluginInfo;
    const apply_reason = options.find(
      (item) => item.value === Number(reason)
    ).label;
    const apply_source = "PRIVACY_CENTER";
    const did = "";
    const params = {
      // 调试
      apply_quota,
      // apply_quota: 100,
      apply_description,
      apply_reason,
      apply_source,
      did,
    };

    applyQuotaDD(params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * @description: 申请提额  快手
 * @return {*}
 */
function applyPromotionQuotaKS() {
  return new Promise((resolve, reject) => {
    const {
      applicationNum: applyQuota,
      desc: applyDesc,
      reason,
      options,
    } = pluginInfo;
    const applyReason = options.find(
      (item) => item.value === Number(reason)
    ).label;
    
    //  调试
    // const params = { applyQuota, applyDesc, applyReason };
    const params = { applyQuota, applyDesc, applyReason };
    applyQuotaKS(params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * @description: 遮罩开启 运行中
 * @return {*}
 */
function showLoading() {
  let loadDiv = $(`<div></div>`);
  let iconUrl = chrome.runtime.getURL("../asset/img/info.png");
  loadDiv.attr("id", "loadDiv");
  const divStyle =
    "position:fixed;z-index:20000; background-color: rgba(0,0,0,0.4);top: 0;right: 0;bottom: 0;left: 0;display:flex;";
  loadDiv.attr("style", divStyle);
  const divInnerHtml = `
      <div
        style="margin: auto; width: 640px;background: #FFFFFF;border-radius: 4px;padding: 18px 24px;box-sizing: border-box;">
        <div style="font-size: 18px;font-weight: 500;color: #000000;font-size: 18px;margin-bottom: 32px;">
          客易达提额助手
        </div>
        <div
          id="loadTitle"
          style="height: 38px;background: #FFF8E6;border-radius: 2px;border: 1px solid #FFDB94;font-size: 12px;color: #666666;padding-left: 12px;margin-bottom: 24px;display:flex;align-items: center;">
            <img src=${iconUrl} style="width:12px;height:12px;margin-right:6px;" />
            <span>提额程序正在运行中，请勿关闭或随意操作额度管理页面；若连续两次审核不通过，今日将停止提额。</span>
        </div>
        <div style="display: flex;width: 100%;justify-content: space-between;margin-bottom: 40px;">
          <div
            style="width: 266px;height: 150px;background: #F7F8FA;border-radius: 6px;text-align: center;padding-top: 20px;box-sizing:border-box;">
            <p style=" font-size: 14px;color: #666666;font-weight: 400;">今日已查看订单量</p>
            <p style="font-size: 48px;font-weight: 600;color: #333333;" id="used_quota">${userInfo.used_quota}</p>
          </div>
          <div
            style="width: 266px;height: 150px;background: #F7F8FA;border-radius: 6px;text-align: center;padding-top: 20px;box-sizing:border-box;">
            <p style="font-size: 14px;color: #666666;font-weight: 400;">今日剩余查看次数</p>
            <p style="font-size: 48px;font-weight: 600;color: #333333;" id="unused_quota">${userInfo.unused_quota}</p>
          </div>
        </div>
        <div style="display: flex;flex-direction: row-reverse;width: 100%;">
          <div
            id="stopLoop"
            style="cursor: pointer;width: 88px;height: 36px;background: #FF1616;border-radius: 3px;text-align: center;line-height: 36px;font-size: 14px;color: #FFFFFF;"
            onclick="finishScript()">
            停止
          </div>
        </div>
      </div>
      `;
  loadDiv.html(divInnerHtml);
  $("body").append(loadDiv);
}

/**
 * @description: 提示框
 * @param {*} state
 * @param {*} msg
 * @return {*}
 */
function showMessage(state, msg, delay = 8000) {
  let msgDiv = $("#msgDiv");
  let msgInnerHtml = "";
  if (!msgDiv.html()) {
    msgDiv = $(`<div></div>`);
    msgDiv.attr("id", "msgDiv");
    const msgStyle = `position:fixed;z-index:20001; top: 10%;left: 50%;margin-left:-300px; width:600px;border-radius:4px;height: 46px;line-height:46px;padding-left:15px;font-size:14px;background:#E0F3D7;`;
    msgDiv.attr("style", msgStyle);
    msgDiv.style = `position:fixed;z-index:20001; top: 10%;left: 50%;margin-left:-300px; width:600px;border-radius:4px;height: 46px;line-height:46px;padding-left:15px;font-size:14px;background:#E0F3D7;`;
    $("body").append(msgDiv);
  }
  switch (state) {
    case "success":
      msgInnerHtml = `<p>客易达提额助手：提额成功~ 申请结果返回之后将自动进行下一次提额~</p>`;
      break;
    case "message":
      msgInnerHtml = `<p>客易达提额助手：${msg}</p>`;
      break;
    case "doing":
      msgInnerHtml = `<p>客易达提额助手：当前正在进行第<span id='msgInterval'>${msg}</span>次提额，请耐心等候...</p>`;
      break;
    case "onLimit":
      msgInnerHtml = `<p>客易达提额助手：今日提额已达上限，<span id='msgInterval'>明日</span>自动重启，请耐心等候...</p>`;
      break;
    case "error":
      msgDiv.style.background = "#F3D7D7";
      msgInnerHtml = `<p>客易达提额助手：运行异常，<span id='msgInterval'>${msg}</span>秒后将自动重试，请耐心等候...</p>`;
      break;
  }
  msgDiv.html(msgInnerHtml);
  setTimeout(() => {
    msgDiv.remove();
  }, delay);
}
